package com.naicheng.ivote.views;

import java.util.HashMap;
import java.util.List;
import java.util.Random;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.naicheng.ivote.R;
import com.naicheng.ivote.constant.ConstantMine;
import com.naicheng.ivote.doman.BaseResponseEntity;
import com.naicheng.ivote.doman.FindDarenDetail;
import com.naicheng.ivote.doman.Option;
import com.naicheng.ivote.engin.BaseFragmentActivity;
import com.naicheng.ivote.parser.BaseParser;
import com.naicheng.ivote.uiself.LinearLayoutForListView;
import com.naicheng.ivote.uiself.ToastUtils;
import com.naicheng.ivote.volley.Response.Listener;

/**
 * 已竞猜的详情
 * 
 * @Package_Name : com.naicheng.ivote.views
 * @ClassName: FindGuessedItemActivity
 * @author lumeng
 * @date 2014-4-27 下午6:46:05
 * @version V1.0
 */
public class FindGuessedItemActivity extends BaseFragmentActivity {

	private TextView tv_timu_title, tv_timu_time, tv_timu_content,
			tv_userjifen, tv_guize;
	private LinearLayoutForListView ll_timus;
	private EditText et_jifen;
	private TextView tv_input_jifen_1, tv_input_jifen_2, tv_input_jifen_3,
			tv_input_jifen_4;
	private Button bt_jingcai;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.find_item_detail_activity);

		getView(R.id.tv_back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		tv_timu_title = getView(R.id.tv_timu_title);
		tv_timu_time = getView(R.id.tv_timu_time);
		tv_timu_content = getView(R.id.tv_timu_content);
		tv_userjifen = getView(R.id.tv_userjifen);
		tv_guize = getView(R.id.tv_guize);
		ll_timus = getView(R.id.ll_timus);
		et_jifen = getView(R.id.et_jifen);
		tv_input_jifen_1 = getView(R.id.tv_input_jifen_1);
		tv_input_jifen_2 = getView(R.id.tv_input_jifen_2);
		tv_input_jifen_3 = getView(R.id.tv_input_jifen_3);
		tv_input_jifen_4 = getView(R.id.tv_input_jifen_4);
		bt_jingcai = getView(R.id.bt_jingcai);

		tv_guize.setOnClickListener(this);
		tv_input_jifen_1.setOnClickListener(this);
		tv_input_jifen_2.setOnClickListener(this);
		tv_input_jifen_3.setOnClickListener(this);
		tv_input_jifen_4.setOnClickListener(this);
		bt_jingcai.setOnClickListener(this);

		String requestcommand = "quizdetail";
		String id = getIntent().getStringExtra("ID");
		HashMap<String, String> m = new HashMap<String, String>();
		m.put("id", id);
		m.put("userid", ConstantMine.userid);
		getDataFromServer(requestcommand, m, new Listener<JSONObject>() {
			@Override
			public void onResponse(JSONObject response) {
				BaseResponseEntity<FindDarenDetail> entity = new BaseParser<FindDarenDetail>()
						.parserDomain(response, FindDarenDetail.class);
				if (entity != null && entity.getState()) {
					FindDarenDetail singleDomain = entity.getSingleDomain();
					if (singleDomain != null) {
						fillViews(singleDomain);
					} else {
						ToastUtils.getNormalCenterToast(CTX, "无法获取信息");
					}
				} else {
					ToastUtils.getNormalCenterToast(CTX, entity.getMsg());
				}
			}
		}, CTX);
	}

	String selectedOptionID = null;
	int selectedposition = -1;

	protected void fillViews(FindDarenDetail f) {
		tv_timu_title.setText(f.getTitle());
		tv_timu_content.setText(f.getContent());
		tv_timu_time.setText("竞猜截止时间：" + f.getCtime());
		tv_timu_time.setTag(f.getCtime());
		tv_userjifen.setText("您的积分：" + f.getUser_integral());
		tv_userjifen.setTag(f.getUser_integral());
		ll_timus.setAdapter(new JingcaiTimuAdapter(CTX, f.getOptions()));
	}

	public final int TIP_JIFEN_SHURUCUOU = 0;
	public final int TIP_JIFEN_GUIZE = 1;
	public final int TIP_JIFEN_TIMEOUT = 2;

	@Override
	@Deprecated
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case TIP_JIFEN_SHURUCUOU:
			return new AlertDialog.Builder(CTX)
					.setTitle("提示")
					.setMessage(
							"亲，查看您的输入：\n1.积分输入应介于 [0-您的积分] 之间\n2.应该选一个您竞猜的项目")
					.setPositiveButton("知道了", null).create();
		case TIP_JIFEN_GUIZE:
			return new AlertDialog.Builder(CTX)
					.setTitle("竞猜规则")
					.setMessage(
							"1.【1:6.3】 意味着，您选择该选项进行竞猜，输入1积分参加竞猜，成功将奖励您6.3个积分，以此类推。\n2.竞猜奖励可能会随着网友竞猜人数和竞猜积分而随时更新呦，您可保持关注。\n3.同题目，您可重复多次进行竞猜，奖励按照您参加竞猜时的奖励比例进行自动兑奖。\n4.竞猜仅供娱乐消遣!")
					.setPositiveButton("知道了", null).create();
		case TIP_JIFEN_TIMEOUT:
			return new AlertDialog.Builder(CTX).setTitle("提示")
					.setMessage("亲，片刻之前，您所竞猜的题目已经超过了竞猜截止时间。\n\n请您下次早点参加吧！")
					.setPositiveButton("知道了", null).create();
		default:
			break;
		}
		return super.onCreateDialog(id);
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.tv_guize:
			showDialog(TIP_JIFEN_GUIZE);
			break;
		case R.id.tv_input_jifen_1: {
			String jifen = (String) tv_userjifen.getTag();
			if (!TextUtils.isEmpty(jifen)) {
				et_jifen.setText(jifen);
			}
			break;
		}
		case R.id.tv_input_jifen_2: {
			String jifen = (String) tv_userjifen.getTag();
			if (!TextUtils.isEmpty(jifen)) {
				et_jifen.setText(String.valueOf((int) Integer.parseInt(jifen) / 2));
			}
			break;
		}
		case R.id.tv_input_jifen_3: {
			String jifen = (String) tv_userjifen.getTag();
			if (!TextUtils.isEmpty(jifen)) {
				et_jifen.setText(String.valueOf((int) Integer.parseInt(jifen) / 4));
			}
			break;
		}
		case R.id.tv_input_jifen_4: {
			String jifen = (String) tv_userjifen.getTag();
			if (!TextUtils.isEmpty(jifen)) {
				et_jifen.setText(String.valueOf((int) Integer.parseInt(jifen)
						* new Random().nextInt()));
			}
			break;
		}
		case R.id.bt_jingcai:
			String shurujifen = et_jifen.getText().toString();
			if (TextUtils.isEmpty(shurujifen)) {
				showDialog(TIP_JIFEN_SHURUCUOU);
			} else {
				String jifen = (String) tv_userjifen.getTag();
				int parseshurujifen = Integer.parseInt(shurujifen);
				if (parseshurujifen <= 0
						|| parseshurujifen > Integer.parseInt(jifen)) {
					showDialog(TIP_JIFEN_SHURUCUOU);
				} else {
					if (selectedposition == -1) {
						showDialog(TIP_JIFEN_SHURUCUOU);
					} else {
						jingcai(shurujifen);
					}
				}
			}
			break;
		default:
			break;
		}
	}

	private void jingcai(String shurujifen) {
		String requestcommand = "quiz";
		String id = getIntent().getStringExtra("ID");
		HashMap<String, String> m = new HashMap<String, String>();
		m.put("id", id);
		m.put("optionid", selectedOptionID);
		m.put("integral", shurujifen);
		m.put("userid", ConstantMine.userid);
		getDataFromServer(requestcommand, m, new Listener<JSONObject>() {
			@Override
			public void onResponse(JSONObject response) {
				BaseResponseEntity<String> entity = new BaseParser<String>()
						.parserString(response);
				if (entity != null && entity.getState()) {
					ToastUtils.getNormalCenterToast(CTX, entity.getMsg());
					finish();
				} else {
					ToastUtils.getNormalCenterToast(CTX, entity.getMsg());
				}
			}
		}, CTX);
	}

	public class JingcaiTimuAdapter extends BaseAdapter {
		private Context context;
		private LayoutInflater mInflater;
		private List<Option> list;

		public JingcaiTimuAdapter(Context context, List<Option> list) {
			this.context = context;
			this.list = list;
			this.mInflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Option getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.jingcai_timu_item,
						null);

				holder.options_item_ll = (LinearLayout) convertView
						.findViewById(R.id.options_item_ll);
				holder.options_item_tv = (TextView) convertView
						.findViewById(R.id.options_item_tv);
				holder.options_item_line = (TextView) convertView
						.findViewById(R.id.options_item_line);
				holder.options_item_per = (TextView) convertView
						.findViewById(R.id.options_item_per);
				holder.options_item_beishu = (TextView) convertView
						.findViewById(R.id.options_item_beishu);
				convertView.setTag(holder);
				convertView.setId(position);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			Option item = getItem(position);
			if (item.isSelected()) {
				holder.options_item_ll.setBackgroundColor(getResources()
						.getColor(R.color.option_bg));
			} else {
				holder.options_item_ll.setBackgroundColor(getResources()
						.getColor(R.color.splash_hei));
			}
			holder.options_item_ll.setTag(R.id.tag_position, position);
			holder.options_item_ll.setTag(R.id.tag_item, item);
			holder.options_item_ll.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					int nposition = (Integer) v.getTag(R.id.tag_position);
					Option item = (Option) v.getTag(R.id.tag_item);
					item.setSelected(true);
					selectedOptionID = item.getOptionid();
					if (selectedposition != -1) {
						getItem(selectedposition).setSelected(false);
						selectedposition = nposition;
					}
					notifyDataSetChanged();
				}
			});

			holder.options_item_tv.setText(item.getOption_key()
					+ item.getOption_value());
			holder.options_item_beishu.setText(item.getDefault_prize());
			holder.options_item_per.setText("%" + 0);

			int colornum = position % 5;
			switch (colornum) {
			case 0:
				holder.options_item_line.setTextColor(context.getResources()
						.getColor(R.color.option1));
				break;
			case 1:
				holder.options_item_line.setTextColor(context.getResources()
						.getColor(R.color.option2));
				break;
			case 2:
				holder.options_item_line.setTextColor(context.getResources()
						.getColor(R.color.option3));
				break;
			case 3:
				holder.options_item_line.setTextColor(context.getResources()
						.getColor(R.color.option4));
				break;
			}
			int pernum = 0;
			int linenum = (pernum * 45) / 100;
			StringBuffer buf = new StringBuffer();
			for (int i = 0; i < linenum; i++) {
				buf.append("|");
				holder.options_item_line.setText(buf.toString());
			}
			return convertView;
		}

		public class ViewHolder {
			public TextView options_item_tv;
			public TextView options_item_line;
			public TextView options_item_per;
			public TextView options_item_beishu;
			public LinearLayout options_item_ll;
		}

	}
}
